<template>
  <div class="main-contain">
    <el-container>
      <el-main>
        <el-row :gutter="2" align="middle">
          <el-col :span="2">协议:</el-col>
          <el-col :span="3">
            <el-select
              v-model="form.protocol"
              placeholder="http"
              clearable
            >
              <el-option label="Http" value="http"/>
              <el-option label="https" value="https"/>
            </el-select>
          </el-col>
          <el-col :offset="1" :span="2"> URL:</el-col>
          <el-col :span="8">
            <el-input v-model="form.url"/>
          </el-col>
        </el-row>

        <div class="i-data-card">
          <el-card
            style="margin-top: 10px"
            shadow="always"
            v-for="(domain, index) in dynamicValidateForm.domains"
            :key="domain.key"
            :label="'Step ' + index"
            :prop="'domains.' + index + '.value'"
            :header="'步骤' + domain.key"
          >
            <el-row align="middle">
              <el-col :span="3">
                操作类型:
              </el-col>
              <el-col :span="4">
                <el-select
                  v-model="domain.type"
                  placeholder="请选择"
                  clearable>
                  <el-option label="输入框" value="1"/>
                  <el-option label="时间选择器" value="2"/>
                  <el-option label="按钮" value="3"/>
                  <el-option label="等待元素加载" value="4"/>
                </el-select>
              </el-col>
            </el-row>

            <el-row align="middle">

              <el-col :span="3">选择器类型:</el-col>
              <el-col :span="4">
                <el-select
                  v-model="domain.pathType"
                  placeholder="请选择"
                  clearable
                >
                  <el-option label="xpath选择器" value="1"/>
                  <el-option label="JS选择器" value="2"/>
                </el-select>
              </el-col>
              <el-col :offset="1" :span="3">选择器路径:</el-col>
              <el-col :span="8">
                <el-input placeholder="选输入" v-model="domain.path"/>
              </el-col>
            </el-row>

            <el-row align="middle" v-show="domain.type != '3' && domain.type != '4'">
              <el-col :span="3">
                <span>输入内容</span>
              </el-col>
              <el-col :span="4">
                <el-input placeholder="输入内容" v-model="domain.value"/>
              </el-col>
            </el-row>

            <el-row align="middle" v-show="domain.type != '3' && domain.type != '4'">
              <el-col :span="3">
                <span>执行之后等待</span>
              </el-col>
              <el-col :span="4">
                <el-input-number placeholder="输入内容" v-model="domain.waitTime" suffix-icon=""/>
              </el-col>
              <el-col :span="3">
                <span>单位:秒</span>
              </el-col>
            </el-row>

            <el-row align="middle" justify="end">
              <el-button class="mt-2" icon="Delete" @click.prevent="removeDomain(domain)">删除</el-button>
            </el-row>
          </el-card>
        </div>
        <el-row class="bottom-button">
          <el-col :span="4">
            <el-button type="default" @click="addDomain">添加step</el-button>
          </el-col>

        </el-row>

        <el-row class="bottom-button">
          <el-col :offset="4" :span="3">
            <el-button type="success" icon="Check" @click="checkParam">校验参数</el-button>
          </el-col>
          <el-col :span="3">
            <el-button type="success" icon="Check" @click="showJson">展示JSON</el-button>
          </el-col>
          <el-col :span="3">
            <el-button type="info" icon="Check" @click="lastConfig">最近配置</el-button>
          </el-col>
          <el-col :span="3">
            <el-button type="success" icon="Check" @click="saveJsonDb">保存配置</el-button>
          </el-col>
          <el-col :span="3">
            <el-button type="danger" icon="Refresh" @click="resetForm">清空</el-button>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" icon="Search" @click="onSubmit">执行</el-button>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
  </div>


  <el-dialog v-model="dialogFormVisible" title="配置json内容">

    <div class='content'>
      <el-button @click="jsonFormat">格式化</el-button>
      <el-button @click="jsonNoFormat">压缩</el-button>
      <el-button @click="callBackToForm">回填</el-button>
      <v-ace-editor v-model:value="dataForm.textareashow" @init="jsonFormat" lang="json" :theme="aceConfig.theme"
                    :options="aceConfig.options" :readonly="aceConfig.readOnly" style="height:300px;margin-top: 20px;"
                    class="ace-editor"/>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import {reactive, h, ref} from 'vue'
import {ipcApiRoute} from '@/api/main';
import {ipc} from '@/utils/ipcRenderer';
import {ElMessage, ElMessageBox} from 'element-plus'
import {VAceEditor} from 'vue3-ace-editor';

import 'ace-builds/src-noconflict/mode-json';
import 'ace-builds/src-noconflict/theme-chrome';
import 'ace-builds/src-noconflict/ext-language_tools';

//ace编辑器配置
const aceConfig = reactive({
  lang: 'json', //解析json
  theme: 'chrome', //主题
  readOnly: false, //是否只读
  options: {
    enableBasicAutocompletion: true,
    enableSnippets: true,
    enableLiveAutocompletion: true,
    tabSize: 2,
    showPrintMargin: false,
    fontSize: 13
  }
});

const form = reactive({
  protocol: "",
  url: '',
})

const dialogFormVisible = ref(false)

const dynamicValidateForm = reactive<{
  domains: DomainItem[]
  email: string
}>({
  domains: [
    {
      key: 1,
      type: '1',
      path: '',
      pathType: '',
      waitTime: 0,
      value: ''
    },
  ],
  email: '',
})

interface DomainItem {
  //步骤
  key: number
  //类型：1:输入框、2:时间选择器、3:按钮,4:等待元素加载
  type: string
  //地址
  path: string
  //选择器地址类型： 1-xpath,2-JS选择器
  pathType: string
  //等待时长
  waitTime: number,
  //输入框输入的值
  value: string
}

const removeDomain = (item: DomainItem) => {
  const index = dynamicValidateForm.domains.indexOf(item)
  if (index !== -1) {
    dynamicValidateForm.domains.splice(index, 1)
  }
}

const addDomain = () => {
  console.log(dynamicValidateForm.domains.length);
  let key = dynamicValidateForm.domains.length + 1
  dynamicValidateForm.domains.push({
    key: key,
    type: '1',
    path: '',
    pathType: '',
    waitTime: 0,
    value: '',
  })
}

function resetForm() {
  dynamicValidateForm.domains = [];
  dynamicValidateForm.domains.push({
    key: 1,
    type: '1',
    path: '',
    pathType: '',
    waitTime: 0,
    value: '',
  });
  form.protocol = "";
  form.url = '';
}

const onSubmit = () => {
  const data = reactive({
    loadAddress: form,
    steps: dynamicValidateForm.domains
  });
  const dataStr = JSON.stringify(data)
  console.log('data:', dataStr)
  ipc.invoke(ipcApiRoute.startGoogleBrowser, dataStr).then(res => {
    console.log('res:', res);
    const data = res.data || null;
    ElMessageBox.confirm(`'go服务返回:${data}'`, 'info');
  })

}

function callBackToForm() {
  const  json = dataForm.textareashow ;
  // const data = reactive({
  //   loadAddress: form,
  //   steps: dynamicValidateForm.domains
  // });
  const obj = JSON.parse(json);
  form.url = obj.loadAddress.url;
  form.protocol = obj.loadAddress.protocol;
  dynamicValidateForm.domains= obj.steps;
  dialogFormVisible.value = false
}

function checkParam(): void {
  ipc.invoke(ipcApiRoute.saveConfig, {}).then(result => {
    dialogFormVisible.value = true
    dataForm.textareashow = result
  })
}

function saveJsonDb() {
  const data = reactive({
    loadAddress: form,
    steps: dynamicValidateForm.domains
  });
  const dataStr = JSON.stringify(data)

  const paramter = {
    tableName: "spider_json",
    json: dataStr
  };
  ipc.invoke(ipcApiRoute.saveConfig, paramter).then(result => {
    console.log(result)
    if (result.code === 0) {
      ElMessage({
        message: '保存成功',
        type: 'success',
      })
      return;
    }
    ElMessage({
      message: '保存失败',
      type: 'error',
    })
  })

}

function showJson() {
  const data = reactive({
    loadAddress: form,
    steps: dynamicValidateForm.domains
  });
  const dataStr = JSON.stringify(data)

  dialogFormVisible.value = true
  dataForm.textareashow = dataStr

}

function lastConfig() {

  ipc.invoke(ipcApiRoute.lastConfig, {}).then(result => {
    dialogFormVisible.value = true
    console.log(result)
    dataForm.textareashow = result.result.json
  })
}


//form
const dataForm = reactive({
  textareashow: '{}'
});

const jsonError = (e) => {
  ElMessageBox.alert(`JSON字符串错误：${e.message}`)
}

// JSON格式化
const jsonFormat = () => {
  try {
    dataForm.textareashow = JSON.stringify(JSON.parse(dataForm.textareashow), null, 2)
  } catch (e) {
    jsonError(e)
  }
};

// JSON压缩
const jsonNoFormat = () => {
  try {
    dataForm.textareashow = JSON.stringify(JSON.parse(dataForm.textareashow))
  } catch (e) {
    jsonError(e)
  }
}


</script>

<style lang="less" scoped>
.main-contain {
  margin-top: 0;
}

.i-data-card {
  margin-top: 50px;
}

.el-row {
  margin-bottom: 20px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.bottom-button {
  margin-bottom: 50px;
}
</style>
